package com.tianxin.workbao.workBao.helper;

import android.content.Context;

import com.tianxin.workbao.workBao.bean.DaoMaster;
import com.tianxin.workbao.workBao.bean.DaoSession;
import com.tianxin.workbao.workBao.common.Constant;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * Created by hacker on 2017/6/17.
 */

public class GreenDaoHelper {
    private static  final String   TAG = GreenDaoHelper.class.getSimpleName()+"--------->";
    private static  final String  DB_NAME=Constant.DB;//数据库名称
    private  DaoMaster.DevOpenHelper devOpenHelper;
    private  DaoMaster daoMaster;
    private  DaoSession daoSession;
    private  Context mContext;
    private static GreenDaoHelper mInstance;

    private GreenDaoHelper() {
    }

    public static GreenDaoHelper newInstance() {
        if (mInstance == null) {
            synchronized (GreenDaoHelper.class) {
                mInstance = new GreenDaoHelper();
            }
        }
        return mInstance;
    }

    /**
     * 初始化Context对象
     * @param context
     */
    public void init(Context context){
        this.mContext = context;
    }

    public  DaoMaster.DevOpenHelper getDevOpenHelper() {
        if (devOpenHelper == null) {
            devOpenHelper = new DaoMaster.DevOpenHelper(mContext,DB_NAME, null);
        }
        return devOpenHelper;
    }

    public DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            daoMaster = new DaoMaster(getDevOpenHelper().getWritableDb());
        }
        return daoMaster;
    }

    public DaoSession getDaoSession() {
        if (daoSession == null) {
            daoSession = getDaoMaster().newSession();
        }
        return daoSession;
    }

    /**
     * 设置debug模式开启或关闭，默认关闭
     * @param flag
     */
    public void setDebug(boolean flag){
        QueryBuilder.LOG_SQL = flag;
        QueryBuilder.LOG_VALUES = flag;
    }


    /**
     * 关闭数据库
     */
    public void closeDataBase(){
        closeHelper();
        closeDaoSession();
    }

    public void closeDaoSession(){
        if (null != daoSession){
            daoSession.clear();
            daoSession = null;
        }
    }

    public  void  closeHelper(){
        if (devOpenHelper!=null){
            devOpenHelper.close();
            devOpenHelper = null;
        }
    }
}
